<template>
    <Layout>
        <Form ref="form1" :model="dataToQuery" :label-width="90">
            <Row v-show="!switchFlag" class="query-form">
                <Col span="6">
                    <FormItem label="企业名称：" prop="order">
                        <cascader-dom class="query-form-el" ref='queryOrgCascader' @setOrgInfo='setQueryCompanyName' :orgTree="true"
                                      :setCurrentName="{label:dataToQuery.companyName,value:dataToQuery.companyId}"></cascader-dom>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="姓名：" >
                        <Input  class=''  type='text' v-model='dataToQuery.userName'></Input>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label='角色：' prop='roleId'>
                        <Select v-model='dataToQuery.roleId' placeholder="请选择角色" class='query-form-el'>
                            <Option v-for="item in dictMap.roles" :value="item.roleId" :key="item.roleId">{{item.roleName }}
                            </Option>
                        </Select>
                    </FormItem>
                </Col>
                <Col span="6" >
                    <Button @click="reset" class="ivu-btn-reset">重置</Button>
                    <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
            <Row class="query-form">
                <Col span="24">
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo1('add')">角色人员新增</Button>
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo1('edit')">角色人员变更</Button>
                    <Button size="large" class="ivu-btn-add" icon="md-add" @click="addInfo1('del')">角色人员删除</Button>
                </Col>
            </Row>
        </Form>
        <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!"
               :loading='pageStatus.loading'
               border :columns="columns1" :data="dataTable">
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
                      @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
                      show-elevator/>
            </Col>
        </Row>

        <Modal :transfer=false footer-hide v-model="userManagerModel" :width=900>
            <userManager :model="true" :companyId="dataToView.companyId" v-if="userManagerModel" @getSelectModelData="getSelectModelData">
            </userManager>
        </Modal>

        <Modal :title="this.getModalTitle(title)" :transfer=false :mask-closable="false" v-model="dialogShow" v-if="dataToView && dialogShow"  :width=800 :styles="{height:'400px'}" class-name='limit-height-dialog'>
            <Row>
                <Col span="24">
                    <Form ref="dialogForm" :class="mode === 'view'?'modal-view-detail':''" :show-message="false" :model="dataToView" :rules="mode === 'view'?{}:ruleCustom" :label-width="mode === 'view'?160:null" :label-position="mode === 'view'?'right':'top'">
                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='企业名称：' prop='companyId'>
                                    <div v-if="mode === 'view'">{{dataToView.companyName}}</div>
                                    <cascader-dom v-else class='query-form-el' ref='orgCascader' @setOrgInfo='setCompanyId' @setOrgname="setCompanyName" :orgTree="true"
                                                  :currentOrgId="dataToView.companyId" :rootOrgId="dataToView.belongOrgId"
                                                  :setCurrentName="{label:dataToView.companyName,value:dataToView.companyId}" ></cascader-dom>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='角色：' prop='roleId'>
                                    <div v-if="mode === 'view'">{{ dataToView.roleName }}</div>
                                    <Select v-else v-model='dataToView.roleId' placeholder="请选择角色" @on-change="adminTypeChange" class='query-form-el'>
                                        <Option v-for="item in dictMap.roles" :value="item.roleId" :key="item.roleId">{{item.roleName }}
                                        </Option>
                                    </Select>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row v-if="dataToView.applyType!=='edit'" type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11" v-if="dataToView.applyType==='del'">
                                <FormItem label='删除的人员：' prop='adminUserIdBefore'>
                                <div v-if="mode === 'view'">{{ dataToView.adminUserIdBeforeName }}</div>
                                    <div v-else>
                                        <Select v-if="show1" v-model='dataToView.adminUserIdBefore' placeholder="请选择审批人" class='query-form-el'>
                                            <Option v-for="item in dictMap.roleUsers" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                                                <span>{{item.userName }}</span>
                                                <span style="float:right;color:#ccc">{{item.companyName }}</span>
                                            </Option>
                                        </Select>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="11" v-else>
                                <FormItem label='人员姓名：' prop='adminUserId'>
                                    <div v-if="mode === 'view'">{{ dataToView.adminUserName }}</div>
                                    <div v-else>
                                        <Input class='query-form-el' placeholder="请选择管理员" type='text'
                                               v-model='dataToView.adminUserName' @on-focus="userManagerModel=true" readonly  suffix="ios-search"></Input>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='审批人：' prop='applyUserId'>
                                    <div v-if="mode === 'view'">{{ dataToView.applyUserName }}</div>
                                    <!--<Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly v-model='dataToView.applyUserName'></Input>-->
                                    <div v-else>
                                        <Select v-if="show" v-model='dataToView.applyUserId' placeholder="请选择审批人" class='query-form-el'>
                                            <Option v-for="item in dictMap.applyUsers" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                                                <span>{{item.userName }}</span>
                                                <span style="float:right;color:#ccc">{{item.companyName }}</span>
                                            </Option>
                                        </Select>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>

                        <Row v-if="dataToView.applyType==='edit'" type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='变更前姓名：' prop='adminUserIdBefore'>
                                    <div v-if="mode === 'view'">{{ dataToView.adminUserIdBeforeName }}</div>
                                    <div v-else>
                                        <Select v-if="show1" v-model='dataToView.adminUserIdBefore' placeholder="请选择审批人" class='query-form-el'>
                                            <Option v-for="item in dictMap.roleUsers" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                                                <span>{{item.userName }}</span>
                                                <span style="float:right;color:#ccc">{{item.companyName }}</span>
                                            </Option>
                                        </Select>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='变更后姓名：' prop='adminUserId'>
                                    <div v-if="mode === 'view'">{{ dataToView.adminUserName }}</div>
                                    <div v-else>
                                        <Input class='query-form-el' placeholder="请选择管理员" type='text'
                                               v-model='dataToView.adminUserName' @on-focus="userManagerModel=true" readonly  suffix="ios-search"></Input>
                                    </div>
                                </FormItem>
                            </Col>
                        </Row>
                        <Row v-if="dataToView.applyType==='edit'" type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='审批人：' prop='applyUserId'>
                                    <div v-if="mode === 'view'">{{ dataToView.applyUserName }}</div>
                                    <div v-else>
                                        <Select v-if="show" v-model='dataToView.applyUserId' placeholder="请选择审批人" class='query-form-el'>
                                            <Option v-for="item in dictMap.applyUsers" :value="item.userId" :disabled="item.disabled" :label="item.userName" :key="item.userId">
                                                <span>{{item.userName }}</span>
                                                <span style="float:right;color:#ccc">{{item.companyName }}</span>
                                            </Option>
                                        </Select>
                                    </div>
                                </FormItem>
                            </Col>
                            <Col span="11"></Col>
                        </Row>

                        <Row type="flex" justify="space-around" class="code-row-bg">
                            <Col span="11">
                                <FormItem label='申请人：' prop='createUserName'>
                                    <div v-if="mode === 'view'">{{ dataToView.createUserName }}</div>
                                    <Input v-else class='query-form-el' placeholder="请填写填报人" type='text' readonly
                                           v-model='dataToView.createUserName'></Input>
                                </FormItem>
                            </Col>
                            <Col span="11">
                                <FormItem label='填报时间：' prop='createDate'>
                                    <div v-if="mode === 'view'">{{ renderViewDate(dataToView.createDate) }}</div>
                                    <DatePicker v-else class="query-form-el" placeholder="请选择填报时间" readonly
                                                v-model='dataToView.createDate'></DatePicker>
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Col>
            </Row>
            <div slot="footer">
                <Button v-if="mode != 'view'" type="primary" :loading="pageStatus.sending" class='ivu-btn-save' @click="submit('dialogForm')" >上报</Button>
                <Button v-if="mode != 'view'" type="primary"  class='ivu-btn-cancel' @click="handleCancel" >取消</Button>
                <Button v-if="mode === 'view'" class='ivu-btn-save' @click="dialogShow=false">关闭</Button>
            </div>
        </Modal>
        <Modal :transfer=false v-model="model4"  :width=900>
            <Tabs>
                <TabPane label="历史记录">
                    <Table ref='table1' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0" :loading="loading2"
                           :data="history" width="100%"  :height="450" highlight-row stripe size="small"></Table>
                </TabPane>
                <TabPane label="流程图">
                    <div style="height: 450px; overflow-y: auto; overflow-x: auto">
                        <img :src="imgUrl" >
                    </div>
                </TabPane>
            </Tabs>
            <div slot="footer">
                <Button @click="model4=false" class="ivu-btn-save">关闭</Button>
            </div>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api/index.js'
    import pageCommonFunction from '@/components/pageCommonFunction.js'
    import {sessionStorage} from "@/common/cacheUtils";
    import userManager from "./userManager";

    var cascaderDom = () => import('@/components/cascader-dom.vue');

    export default {
        components: {
            cascaderDom,userManager
        },
        data() {
            return {
                ...this.createCommonDataField(),
                userManagerModel:false,
                columns1: [
                    {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
                    {
                        title: '状态',
                        align: 'center',
                        fixed:'left',
                        key: 'status',
                        width: 100,
                        render: (h, params) => {
                            let color = 'green';
                            if (params.row.procinstState == undefined || params.row.procinstState == null || params.row.procinstState == 2) {
                                color = 'red';
                            }
                            if (params.row.procinstState == 1) {
                                color = 'blue';
                            }
                            return h('div', [
                                h('span', {
                                    style: {
                                        color: color
                                    }
                                }, params.row.procinstState == 1 ? '审批中' : params.row.procinstState == 2 ? '审批不通过' : params.row.procinstState == 3 ? '审批通过' :params.row.procinstState == 5 ?'已终止': '未上报' || '--')
                            ]);
                        }
                    },
                    {key: 'applyType', title: '申请类型', align: 'center', minWidth: 100,
                        render: (h, params) => {
                            return h('span',  params.row.applyType ==='add' ? '添加' : params.row.applyType === 'edit' ? '修改' : params.row.applyType === 'del' ? '删除' : '')

                        }},
                    {key: 'roleName', title: '角色', align: 'center', minWidth: 160,tooltip:true},
                    {key: 'adminUserName', title: '变更后姓名', align: 'center', minWidth: 100},
                    {key: 'adminUserIdBeforeName', title: '变更前姓名', align: 'center', minWidth: 100},
                    {key: 'createUserName', title: '申请人', align: 'center', minWidth: 100},
                    {key: 'applyTime',  title: '申请时间', align: 'center', minWidth: 100,render:this.renderCellDate},
                    {key: 'applyUserName', title: '审批人', align: 'center', minWidth: 100},
                    {key: 'companyName', title: '所属单位', align: 'center', minWidth: 180},
                    {key: 'belongOrgName', title: '所属二级集团', align: 'center', minWidth: 180},
                    {
                        title: '操作',
                        key: 'action',
                        fixed: 'right',
                        width: 140,
                        align: 'center',
                        render: (h, params) => {
                            let flag = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',

                                    },
                                    on: {
                                        click: () => {
                                            this.viewData(params);
                                        }
                                    }
                                }, '详情'),
                                // h('Divider', {
                                //     props: {
                                //         type: 'vertical',
                                //     }
                                // }, ''),
                                // h('A', {
                                //     props: {
                                //         type: 'primary',
                                //         size: 'small'
                                //     },
                                //     style: {
                                //         fontSize: '14px',
                                //         color: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? '#d0d0d0':flag ? '':'#d0d0d0',
                                //         pointerEvents: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? 'none' :  flag ? '' : 'none'
                                //     },
                                //     on: {
                                //         click: () => {
                                //             this.editData(params);
                                //         }
                                //     }
                                // }, '修改'), h('Divider', {
                                //     props: {
                                //         type: 'vertical',
                                //     }
                                // }, ''),
                                // h('A', {
                                //     props: {
                                //         type: 'primary',
                                //         size: 'small'
                                //     },
                                //     style: {
                                //         fontSize: '14px',
                                //         color:  params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? '#d0d0d0': flag ? '':'#d0d0d0',
                                //         pointerEvents: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? 'none' :  flag? '' : 'none'
                                //     },
                                //     on: {
                                //         click: () => {
                                //             this.$Modal.confirm({
                                //                 title: '提示',
                                //                 content: '<p>是否要提交？</p>',
                                //                 onOk: () =>{
                                //                     this.reportInfo(params.row);
                                //                 } ,
                                //                 onCancel: () => {
                                //                 }
                                //             });
                                //         }
                                //     }
                                // }, '上报'),
                                // h('Divider', {
                                //     props: {
                                //         type: 'vertical',
                                //     }
                                // }, ''),
                                // h('A', {
                                //     props: {
                                //         type: 'error',
                                //         size: 'small'
                                //     },
                                //     style: {
                                //         fontSize: '14px',
                                //         color:  params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? '#d0d0d0': flag ? 'red':'#d0d0d0',
                                //         pointerEvents: params.row.procinstState == "1" || params.row.procinstState == "2" || params.row.procinstState == "3" ? 'none' : flag ? '' : 'none'
                                //     },
                                //     on: {
                                //         click: () => {
                                //             this.deleteData(params);
                                //         }
                                //     }
                                // }, '删除'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('a', {
                                    props: {
                                        type: 'primary',
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: params.row.procinstId == null ? '#d0d0d0' : '',
                                        pointerEvents: params.row.procinstId == null ? 'none' : ''
                                    },
                                    on: {
                                        click: () => {
                                            this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                                            this.showHistory(params.row);
                                        }
                                    }
                                },'审批记录')
                            ]);
                        }
                    }
                ],
                ruleCustom: {
                    roleId: [ { required: true, message: '请选择角色', trigger: 'change',}],
                    adminUserId: [ { required: true, message: '请选择管理员姓名', trigger: 'change',}],
                    applyUserId: [ { required: true, message: '审批人不能为空', trigger: 'change',}],
                    adminUserIdBefore: [ { required: true, message: '请选择更改后姓名', trigger: 'change',}],
                },
                currentUser:sessionStorage('userId').getObject('userId'),
                tableHeight: 10,
                dictMap: {
                    roles:[],//所有角色
                    roleUsers:[],//角色中人员
                    applyUsers:[],//审批人
                },
                // api
                queryUrl: Api.queryRoleUserApply,
                deleteUrl: Api.deleteRoleUserApply,
                updateUrl: Api.updateRoleUserApply,
                saveUrl: Api.saveRoleUserApply,
                show:true,
                show1:true,
                title:'',
                applyType:'',

                imgUrl:'',
                history:[],
                model4:false,
                loading2:false,
                columns2: [
                    {type: 'index', title: '序号', width: 80, align: 'center',},
                    {width: 180, title: '审批时间', key: 'endTime', align: 'center',},
                    {width: 185, title: '节点名称', key: 'name', align: 'center',},
                    {width: 120, title: '审批人', key: 'userName', align: 'center'},
                    {width: 100, title: '审批意见', key: 'route', align: 'center'},
                    {width: 200, title: '备注', key: 'opinions', align: 'center'},
                ],
            }
        },
        async mounted() {
            this.setTableHeight();
            await this.$http.get(Api.getAllUserRoleConfigure).then((res) => {
                this.dictMap.roles = res.data.data
            }).catch(e => {
                this.$Message.error("数据字典获取失败")
            });
            this.pageStatus.baseDataloading = false
            this.query();
        },
        methods: {
            ...pageCommonFunction,

            showHistory(row) {
                this.model4 = true;
                this.loading2 = true;
                this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
                    this.history = res.data;
                    this.loading2 = false;
                }).catch(e => {
                    this.$Message.error("数据获取失败")
                })
            },

            adminTypeChange(val){
                this.$set(this.dataToView,'adminUserId',undefined)
                this.$set(this.dataToView,'adminUserName',undefined)
                this.dataToView.adminUserIdBefore = undefined
                this.dataToView.adminUserIdBeforeName = undefined
                this.show =false
                let roleMap = this.dictMap.roles.find(m=>m.roleId===val)
                let data = {};
                data.fromPage = 1;
                data.pageSize = 100;
                data.roleId = roleMap.applyRoleId;
                if (roleMap.roleName.indexOf("负责人") > -1) {
                    if (roleMap.roleName.indexOf("企业") > -1) {
                        data.orgId = this.dataToView.belongOrgId;
                    }
                } else {
                    data.orgId = this.dataToView.companyId;
					// data.companyName = this.dataToView.companyName;
                }
                this.$http.get(Api.queryUserInRole, {params : data}).then(res => {
                    this.dictMap.applyUsers = res.data.data;
                    this.$nextTick(()=>{
                        this.show =true
                    })
                })

                this.show1 =false
                let data1 = {};
                data1.fromPage = 1;
                data1.pageSize = 100;
                data1.roleId = roleMap.roleId;
                data1.orgId = this.dataToView.companyId;
				// data1.companyName = this.dataToView.companyName;
                this.$http.get(Api.queryUserInRole, {params : data1}).then(res => {
                    this.dictMap.roleUsers = res.data.data;
                    this.$nextTick(()=>{
                        this.show1 =true
                    })
                })
            },
            deleteData(params) {
                this.deleteDateAjax(params);
            },
            addInfo1(type){
                this.applyType = type
                this.title = type==='add'?'角色人员新增':type==='edit'?'角色人员替换':type==='del'?'角色人员删除':''
                this.addInfo()
            },
            async beforeEditDialogOpen(data) {
            },
            query() {
                this.dataToQuery.type = 2
                this.queryAjax();
            },
            submit(name) {
                if (this.pageStatus.sending) return
                let _this = this
                _this.$refs[name].validate((valid) => {
                    if (valid) {
                        _this.$Modal.confirm({
                            title: '提示',
                            content: '<p>上报后不可修改，是否要上报？</p>',
                            onOk: () =>{
                                this.pageStatus.sending = true
                                _this.$http.post(_this.saveUrl, _this.dataToView).then((res) => {
                                    if (res.data.status === 200) {
                                        let user = sessionStorage('userId').getObject('userId')
                                        let data = {
                                            key: "roleManagerUserApply",
                                            createUserId: user.userId,
                                            userName: user.userName,
                                            workId: _this.dataToView.id,
                                            type:"userChangeApply",
                                            formKey: "roleManagerUserApproval",
                                            user1: _this.dataToView.applyUserId,
                                        };
                                        _this.$http.post(Api.submit, data).then((res)=> {
                                            _this.dialogShow = false;
                                            _this.$Message.success('上报成功');
                                            _this.query();
                                            _this.pageStatus.sending = false
                                        }).catch(e => {
                                            _this.$Message.error('上报失败')
                                            _this.pageStatus.sending = false
                                        })
                                    } else if (res.data.status === 201) {
                                        _this.$Message.error(res.data.msg);
                                        _this.pageStatus.sending = false
                                    }
                                }).catch(e => {
                                    _this.$Message.error('上报失败')
                                    _this.pageStatus.sending = false
                                })
                            } ,
                            onCancel: () => {
                            }
                        });
                    } else {
                        _this.$Message.error('请填报完整!');
                    }
                })
            },
            getSelectModelData(row) {
                this.$set(this.dataToView,'adminUserId',row.userId)
                this.$set(this.dataToView,'adminUserName',row.userName)
                this.userManagerModel = false;
            },
            closeModel(){
                this.userManagerModel = false
            },

            handleCancel() {
                this.dataToView = {};
                this.dialogShow = false;
                this.query();
            },
            createEmptyDataToAdd() {
                return {
                    id: this.get_uuid(),
                    applyType: this.applyType,
                    adminType: 'NO'
                }
            }
        },
        watch: {},
    }
</script>

<style lang='css' scoped>
    .rpt-form {
    }

    /deep/ .rpt-form .query-form-el {
        width: 100%;
    }

    /deep/ .rpt-form .ivu-form-item {
        margin-bottom: 24px;
    }

</style>
